import traceback
from pyim import logger
from pyim.auth import login_required
from pyim.handler import BaseHandler
from pyim.user import User


class Handler(BaseHandler):
    @login_required
    def handle(self, connection, packet):
        try:
            msg_id = User.manager.save_message(packet["sender"],
                                               packet["receiver"],
                                               packet["message"])
            packet["message_id"] = msg_id
            logger.debug("%s -> %s = %d" % (packet["sender"], packet["receiver"], msg_id))
            # route(packet, connection)

            # 通过简单的转发实现两个连接的对话
            user = User.manager[packet["receiver"]]
            if user:
                user.connection.route(packet)
        except Exception as e:
            traceback.print_exc()
